// LaserKitService.java
package com.mytech.cslive.services;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

import com.mytech.cslive.dsp.Controller;
import com.mytech.cslive.dsp.Controller.DTMFRecieved;
import com.mytech.cslive.infrastructure.LogFile;

public class LaserKitService extends Service implements DTMFRecieved {
	public static final String TAG = "CSLive.LaserKitService";
	public static final String EXTRA_MESSENGER = "com.mytech.cslive.LaserKitService.EXTRA_MESSENGER";

	private Messenger messenger;

	private Controller dtmfController;

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onDestroy() {
		// Stopping DTMF decoding
		dtmfController.toggleState(false);
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Bundle extras = intent.getExtras();

		if (extras != null) {
			setMessenger((Messenger) extras.get(EXTRA_MESSENGER));
		} else {
			Error e = new Error("No additional handler for" + TAG +" , something is wrong, exiting");
			throw e;
		}

		dtmfController = new Controller(this);

		// Starting DTMF decoding
		dtmfController.toggleState(true);
		
		return Service.START_STICKY;
	}

	private Messenger getMessenger() {
		return messenger;
	}

	private void setMessenger(Messenger messenger) {
		this.messenger = messenger;
	}

	@Override
	public void gotSignal(char recievedSignal) {
		// Handling received signal
		// Important, right now, the message content has no meaning
		if (recievedSignal == '1') {
			notifyPlayerAboutHit();
		} else {
			// Currently do nothing.
		}
	}

	/**
	 * Notifying the player about a hit
	 */
	private void notifyPlayerAboutHit() {

		Message msg = Message.obtain();
		msg.arg1 = 1;

		try {
			getMessenger().send(msg);
		} catch (RemoteException e) {
			LogFile.log(e);
			// And do nothing right now
			e.printStackTrace();
		}
	}
}
